<?php

/**
 * Aurorum - Open source digital signage
 *
 * @link http://digitalsignage.tk
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 *
 * @category Aurorum
 * @package Aurorum
 */

/**
 * This class transmits requested stuff to client.
 *
 * @package Aurorum
 * @subpackage Core
 */

class ADS_Transmitter{

    private $playerId  = -1;
    
    public function listen(ADS_ClientConnection $connection, $ignore = false){
        $pModel = new ADS_PlayerModel();
        if(!$ignore && !$pModel->checkClientKey($connection->clientKey)){
            throw new ADS_InvalidKeyException('Client key is invalid');
        }
        $pModel->updateState($connection->clientKey, array(
            'lastSeen' => date('Y-m-d H:i:s'),
            'version'  => $connection->swVersion
        ));
        $this->playerId = (int)$pModel->resolveClientKey($connection->clientKey)->playerId;
    }

    public function sendDescriptor($format = 'xml'){ 
        $dModel = new ADS_DeploymentModel();
        $deployment = $dModel->getCurrentDeployment();
        //send output
        header('Content-type: application/json');  
        print ($deployment?$deployment->descriptor:json_encode((object)array()));
        
    }
    
    public function sendCommands(){
        $pModel = new ADS_PlayerModel();
        $commands = $pModel->getCommands($this->playerId);
        foreach ($commands as &$command) {
            $command = $command->cmd;
        }
        //send output
        header('Content-type: application/json');
        print json_encode((object) $commands);
    }
    
    public function sendCurrentRevision(){
        $dModel = new ADS_DeploymentModel();
        $deployment = $dModel->getCurrentDeployment();
        //send output
        header('Content-type: application/json');
        print json_encode((object) array(
            'revision' => (int)$deployment?$deployment->deploymentId:0
        ));
    }
        
    public function confirmCommands(){
        $pModel = new ADS_PlayerModel();
        $pModel->confirmCommands($this->playerId);

        print json_encode((object) array('response' => 'ok'));
    }
    
}
